import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_hsh/fluttergromore/ads/ad_feed_view.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'reliang_logic.dart';

class ReliangPage extends StatelessWidget {
  final logic = Get.put(ReliangLogic());

  ReliangPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('每日卡路里记录'),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            // 顶部热量概览区域
            _buildCalorieOverview(),
            
            // 营养素显示区域
            _buildNutrientsDisplay(),
            
            // 餐次类型选择按钮
            _buildMealTypeButtons(),
            const MyAdFeedView(),
            // 饮食记录列表
            _buildFoodRecordsList(),
          ],
        ),
      ),
    );
  }

  // 顶部热量概览 - 圆形进度条
  Widget _buildCalorieOverview() {
    return Container(
      padding: const EdgeInsets.all(10),
      child: Column(
        children: [
          Obx(() {
            double progress = logic.totalCalories.value / 2000.0; // 2000Kcal为每日目标
            if (progress > 1.0) progress = 1.0;
            
            return Column(
              children: [
                // 圆形进度条和中心文本
                SizedBox(
                  width: 160.w,  // 增大容器宽度
                  height: 160.w, // 增大容器高度
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      // 自定义圆形进度条 - 使用整个容器空间
                      CustomPaint(
                        size: Size(160.w, 160.w), // 明确指定绘制区域大小
                        painter: _CircularProgressPainter(
                          progress: progress,
                          strokeWidth: 16, // 增加线条宽度
                          backgroundColor: Colors.grey[200]!,
                          progressColor: progress >= 1.0 ? Colors.red : Colors.blue,
                        ),
                      ),
                      // 当前Kcal值显示在圆心位置
                      SizedBox(
                        width: 200.w, // 增大文本容器
                        child: Text(
                          '${logic.totalCalories.value.toStringAsFixed(0)} Kcal',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: 26.sp, // 增大字体
                            fontWeight: FontWeight.bold,
                            color: progress >= 1.0 ? Colors.red : Colors.blue,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                // 推荐目标显示在进度条下方
                const SizedBox(height: 12),
                Text(
                  '推荐目标: 2000 Kcal',
                  style: TextStyle(
                    fontSize: 16.sp, // 增大字体
                    color: Colors.grey[600],
                  ),
                ),
                // 提示文本
                const SizedBox(height: 8),
                Obx(() {
                  final totalCalories = logic.totalCalories.value;
                  final remainingCalories = 2000 - totalCalories;
                  
                  if (totalCalories >= 2000) {
                    // 超过目标的情况
                    return Text(
                      '已超过${(totalCalories - 2000).toStringAsFixed(0)}卡路里',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.red,
                        fontWeight: FontWeight.w500,
                      ),
                    );
                  } else {
                    // 未达到目标的情况
                    return Text(
                      '还可摄入${remainingCalories.toStringAsFixed(0)}卡路里',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.green,
                        fontWeight: FontWeight.w500,
                      ),
                    );
                  }
                }),
              ],
            );
          }),
          const SizedBox(height: 10),
          const Text(
            '今日卡路里摄入',
            style: TextStyle(fontSize: 16),
          ),
        ],
      ),
    );
  }

  // 营养素显示区域
  Widget _buildNutrientsDisplay() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
      child: Obx(() {
        return Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            _buildNutrientItem('蛋白质', logic.totalProtein.value, 'g'),
            _buildNutrientItem('碳水', logic.totalCarbs.value, 'g'),
            _buildNutrientItem('脂肪', logic.totalFat.value, 'g'),
          ],
        );
      }),
    );
  }

  // 单个营养素项
  Widget _buildNutrientItem(String name, double value, String unit) {
    return Column(
      children: [
        Text(
          '${value.toStringAsFixed(1)}$unit',
          style: const TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        Text(
          name,
          style: const TextStyle(
            fontSize: 14,
            color: Colors.grey,
          ),
        ),
      ],
    );
  }

  // 餐次类型选择按钮
  Widget _buildMealTypeButtons() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildMealButton('早餐', Icons.breakfast_dining, Colors.orange),
          _buildMealButton('午餐', Icons.lunch_dining, Colors.green),
          _buildMealButton('晚餐', Icons.dinner_dining, Colors.purple),
          _buildMealButton('零食', Icons.cookie, Colors.brown),
        ],
      ),
    );
  }

  // 单个餐次按钮
  Widget _buildMealButton(String mealType, IconData icon, Color color) {
    return InkWell(
      onTap: () => logic.showFoodInputDialog(mealType),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
        decoration: BoxDecoration(
          color: color.withOpacity(0.1),
          borderRadius: BorderRadius.circular(20),
          border: Border.all(color: color.withOpacity(0.3)),
        ),
        child: Column(
          children: [
            Icon(icon, color: color, size: 24),
            const SizedBox(height: 4),
            Text(
              mealType,
              style: TextStyle(
                color: color,
                fontSize: 12,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 饮食记录列表
  Widget _buildFoodRecordsList() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      constraints: BoxConstraints(minHeight: 200.h), // 设置最小高度
      child: Obx(() {
        if (logic.foodRecords.isEmpty) {
          return Container(
            height: 200.h,
            child: const Center(
              child: Text(
                '暂无饮食记录',
                style: TextStyle(color: Colors.grey, fontSize: 16),
              ),
            ),
          );
        }

        return Column(
          children: [
            const SizedBox(height: 10),
            Text(
              '饮食记录',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 10),
            ...logic.foodRecords.map((record) => 
              _buildFoodRecordItem(record, logic.foodRecords.indexOf(record))
            ).toList(),
          ],
        );
      }),
    );
  }

  // 单个食物记录项
  Widget _buildFoodRecordItem(dynamic record, int index) {
    return Card(
      margin: const EdgeInsets.symmetric(vertical: 8),
      child: ListTile(
        leading: Icon(
          _getMealTypeIcon(record.mealType),
          color: _getMealTypeColor(record.mealType),
        ),
        title: Text(record.foodName),
        subtitle: Text(
          '${record.timestamp.hour.toString().padLeft(2, '0')}:${record.timestamp.minute.toString().padLeft(2, '0')}',
          style: const TextStyle(fontSize: 12, color: Colors.grey),
        ),
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              '${record.calories.toStringAsFixed(0)} Kcal',
              style: const TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.blue,
              ),
            ),
            IconButton(
              icon: const Icon(Icons.delete, color: Colors.red),
              onPressed: () => _confirmDeleteRecord(index),
            ),
          ],
        ),
      ),
    );
  }

  // 获取餐次类型图标
  IconData _getMealTypeIcon(String mealType) {
    switch (mealType) {
      case '早餐':
        return Icons.breakfast_dining;
      case '午餐':
        return Icons.lunch_dining;
      case '晚餐':
        return Icons.dinner_dining;
      case '零食':
        return Icons.cookie;
      default:
        return Icons.restaurant;
    }
  }

  // 获取餐次类型颜色
  Color _getMealTypeColor(String mealType) {
    switch (mealType) {
      case '早餐':
        return Colors.orange;
      case '午餐':
        return Colors.green;
      case '晚餐':
        return Colors.purple;
      case '零食':
        return Colors.brown;
      default:
        return Colors.grey;
    }
  }

  // 确认删除记录
  void _confirmDeleteRecord(int index) {
    showDialog(
      context: Get.context!,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除这条饮食记录吗？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              logic.deleteFoodRecord(index);
            },
            child: const Text('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }
}

// 自定义圆形进度条绘制器
class _CircularProgressPainter extends CustomPainter {
  final double progress;
  final double strokeWidth;
  final Color backgroundColor;
  final Color progressColor;

  _CircularProgressPainter({
    required this.progress,
    required this.strokeWidth,
    required this.backgroundColor,
    required this.progressColor,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = (size.width - strokeWidth) / 2;

    // 绘制背景圆
    final backgroundPaint = Paint()
      ..color = backgroundColor
      ..style = PaintingStyle.stroke
      ..strokeWidth = strokeWidth;

    canvas.drawCircle(center, radius, backgroundPaint);

    // 绘制进度圆
    final progressPaint = Paint()
      ..color = progressColor
      ..style = PaintingStyle.stroke
      ..strokeWidth = strokeWidth
      ..strokeCap = StrokeCap.round;

    final sweepAngle = 2 * pi * progress;
    canvas.drawArc(
      Rect.fromCircle(center: center, radius: radius),
      -pi / 2, // 从顶部开始
      sweepAngle,
      false,
      progressPaint,
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}